﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Citi.Import.Util;

namespace Citi.GLCosmos.Domain
{
    public partial class Sector
    {
        public object InitializeLifetimeService()
        {
            return null;
        }
        
        public static readonly List<Definition<Sector>> Definitions = new List<Definition<Sector>>
        {
            new Definition<Sector> { ModelProperty = x => x.Code, Required = true, Position = 5,  CustomConversionMethod=ValidateCode},
        };

        private static object ValidateCode(ref Sector model, string value, List<string> fields, ref string error, List<string> headers = null)
        {
            value = value.Trim();
            
            if (string.IsNullOrEmpty(value))
            {
                error = string.Format("The field Code can not be null");
                return Conversion.Validation.Failed;
            }

            var domain = CacheFacade.Get(new Sector().SelectAll<Sector>).FirstOrDefault(x => x.Code == value);

            if (domain != null)
            {
                model = domain;
                return Conversion.Validation.Validated;
            }

            return value;
        }

        public static void Save(List<Sector> sector)
        {
            sector = sector.Distinct(new SectorComparer()).Where(x => x != null && !string.IsNullOrEmpty(x.Code.ToString()) && x.Id == 0).ToList();

            if (!sector.Any()) return;
            sector.First().Save(sector, 250);

            CacheFacade.Clear(typeof(Sector));
        }

        public class SectorComparer : IEqualityComparer<Sector>
        {
            public bool Equals(Sector x, Sector y)
            {
                if (ReferenceEquals(x, y)) return true;
                if (ReferenceEquals(x, null) || ReferenceEquals(y, null))
                    return false;

                return x.Code == y.Code && x.Id == y.Id;
            }

            public int GetHashCode(Sector item)
            {
                if (ReferenceEquals(item, null)) return 0;

                int hashId = item.Code == null ? 0 : item.Id.GetHashCode();
                int hashCode = item.Code.ToString() == null ? 0 : item.Code.GetHashCode();

                return hashId ^ hashCode;
            }
        }

    }
}
